package com.example.jn.checkticketforandroid;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.os.Bundle;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jn on 2016/5/7.
 */
public class GetIDNo extends Activity {
    NfcAdapter nfcAdapter;
    public static final String action = "jason.broadcast.action";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.idhide);

        // 获取默认的NFC控制器
        nfcAdapter = NfcAdapter.getDefaultAdapter(GetIDNo.this);
        if (nfcAdapter == null) {
            // promt.setText("设备不支持NFC！");
            finish();//退出程序
            return;
        }
        if (!nfcAdapter.isEnabled()) {
            // promt.setText("请在系统设置中先启用NFC功能！");
            finish();//退出程序
            return;
        }

      //  finish();

    }


    private void delay(int ms){
        try {
            Thread.currentThread();
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        //得到是否检测到ACTION_TECH_DISCOVERED触发
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
            //处理该intent
            processIntent(getIntent());
        }
    }
    /**       * Parses the NDEF Message from the intent and prints to the TextView       */
    private void processIntent(Intent intent) {
        //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        for (String tech : tagFromIntent.getTechList()) {
            System.out.println(tech);
        }
        boolean auth = false;
        //读取TAG
        MifareClassic mfc = MifareClassic.get(tagFromIntent);
        try {
            String metaInfo = "";
            //Enable I/O operations to the tag from this TagTechnology object.
            mfc.connect();
            int type = mfc.getType();//获取TAG的类型
            int sectorCount = mfc.getSectorCount();
            //获取TAG中包含的扇区数
            String typeS = "";
            switch (type) {
                case MifareClassic.TYPE_CLASSIC:
                    typeS = "TYPE_CLASSIC";
                    break;
                case MifareClassic.TYPE_PLUS:
                    typeS = "TYPE_PLUS";
                    break;
                case MifareClassic.TYPE_PRO:
                    typeS = "TYPE_PRO";
                    break;
                case MifareClassic.TYPE_UNKNOWN:
                    typeS = "TYPE_UNKNOWN";
                    break;
            }
/*            metaInfo += "卡片类型：" + typeS + "\n共" + sectorCount + "个扇区\n共"
                    + mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize() + "B\n";*/
            for (int j = 0; j < 1 /*sectorCount*/; j++) {
                //Authenticate a sector with key A.
                auth = mfc.authenticateSectorWithKeyA(j,  MifareClassic.KEY_DEFAULT);
                int bCount;
                int bIndex;

                if (auth)
                {
                    //  metaInfo += "Sector " + j + ":验证成功\n";
                    // 读取扇区中的块

                    bCount = mfc.getBlockCountInSector(j);
                    bIndex = mfc.sectorToBlock(j);
                    for (int i = 0; i < 1 /*bCount*/; i++) {
                        byte[] data = mfc.readBlock(bIndex);
                        /*metaInfo += "Block " + bIndex + " : "
                                + bytesToHexString(data) + "\n";*/
                        metaInfo += bytesToHexString(data) + "\n";

                        bIndex++;
                    }
                } else {
                    metaInfo += "Sector " + j + ":验证失败\n";
                }
            }
            //iccardno.setText(metaInfo.substring(2, 10));

            String getdata = metaInfo.substring(2, 10);
            getdata = getdata.substring(6,8) + getdata.substring(4,6) + getdata.substring(2,4)+ getdata.substring(0,2);
           String ICcardno = new BigInteger(getdata, 16).toString();
            if (ICcardno != null && !ICcardno.equals(""))
            {
              // System.out.println("卡号："+ICcardno);
                Intent intentNO = new Intent(action);
                intentNO.putExtra("data", ICcardno);
                sendBroadcast(intentNO);
                finish();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //字符序列转换为16进制字符串
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("0x");
        if (src == null || src.length <= 0)
        {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++)
        {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }
    /*
         * Function  :  保存数据到SharedPreferences对象中
         * Param     :  fileName保存数据的文件名；userName、userPswd保存的数据
         * Author    :  博客园-依旧淡然
         */
    public boolean saveDataToSharedPreferences(String fileName,String userName, String userDate) {
        boolean isSaveDataSuccess = false;           //存储数据成功标志位
        SharedPreferences sharedPreferences = this.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();    //创建SharedPreferences.Editor对象
        edit.putString(userName, userDate);        //存储数据
        isSaveDataSuccess = edit.commit();           //提交存储数据
        return isSaveDataSuccess;
    }
    /*
     * Function  :  从SharedPreferences对象中读取数据
     * Param     :  fileName保存数据的文件名
     * Author    :  博客园-依旧淡然
     */
    public String readDataFromSharedPreferences(String fileName,String userName) {
        Map<String, Object> map = new HashMap<String, Object>();            //Map对象，用于存储读取到的数据
        SharedPreferences sharedPreferences = this.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        String resrltstr = sharedPreferences.getString(userName, "");      //读取SharedPreferences对象中的数据
        return resrltstr;
    }
}
